// 云函数入口文件
const cloud = require('wx-server-sdk');
const _ = require('lodash');

cloud.init();
const db = cloud.database();
const PaperSize = 5;
const PaperScore = 100;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const result = await db.collection('garbage').aggregate().sample({ size: PaperSize }).limit(PaperSize).end();
  const question_list = [];
  const question_score = PaperScore/PaperSize;
  _.forEach(result.list, item => {
    const question = { title: item.name, score: question_score, category: item.category };
    const options_list = [
      { id: '1', text: '可回收物', is_right: 0, code: [ 1, 16 ] },
      { id: '2', text: '有害垃圾', is_right: 0, code: [ 2 ] },
      { id: '3', text: '厨余垃圾', is_right: 0, code: [ 4 ] },
      { id: '4', text: '其他垃圾', is_right: 0, code: [ 8 ] }
    ];
    _.forEach(options_list, opts => {
      opts.is_right = _.includes(opts.code, item.category) ? 1 : 0;
    });
    question.options_list = options_list;
    question_list.push(question);
  });
  return question_list;
}